package com.goods.shop.test;

import java.util.Enumeration;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinCalculator implements Calculator {
    private ForkJoinPool pool;
    ForkJoinCalculator(){
        pool=new ForkJoinPool();
    }
    private static class SumTask extends RecursiveTask<Long>{
        private int[] numbers;
        private int from;
        private int to;

        public SumTask(int[] numbers,int from,int to){
            this.numbers=numbers;
            this.from=from;
            this.to=to;
        }
        @Override
        protected Long compute(){
            if(to-from<6){
                long total=0;
                for(int i=from;i<to;i++){
                    total+=numbers[i];
                }
                return total;
            }else{
                int middle=(from + to) >>> 1;;
                SumTask taskLeft=new SumTask(numbers,from,middle);
                SumTask taskRight=new SumTask(numbers,middle,to);
                taskLeft.fork();
                taskRight.fork();
                return taskLeft.join()+taskRight.join();
            }

        }
    }
    @Override
    public long sum(int[] datas) {
        Long result=pool.invoke(new SumTask(datas,0,datas.length));
        pool.shutdown();
        return result;
    }
}
